package com.iss.wyy.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 反射工具类
 */
public class ReflectionUtil {
    /**
     * 反射创建实例
     * 从新封装异常
     */
    public static Object newInstance(Class<?> cls){
        Object instance;
        try {
            instance=cls.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return instance;
    }

    /**
     * 反射给属性赋值
     * @param object
     * @param field
     * @param value
     */
    public static void setField(Object object, Field field,Object value){
        //让private的可以直接访问
        field.setAccessible(true);
        try {
            field.set(object,value);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("set field failure",e);
        }
    }
    public static Object invokeMethod(Object obj, Method method,Object args){
        Object result;
        method.setAccessible(true);
        try {
            result = method.invoke(obj,args);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
